package com.ft.adbix.core.widget;

import android.content.Context;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.ft.adbix.core.R;
import com.ft.adbix.core.interactive.ShakeDetector;

public class ShakeInteractiveView extends FrameLayout {
    private ShakeDetector shakeDetector;
    private Vibrator vibrator;

    public ShakeInteractiveView(@NonNull Context context) {
        this(context,null);
    }

    public ShakeInteractiveView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public ShakeInteractiveView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        View innerView = LayoutInflater.from(context).inflate(R.layout.layout_interactive_shake, this, false);
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        addView(innerView, params);

        // 初始化震动器
//        vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);

        // 初始化摇一摇检测器
        shakeDetector = new ShakeDetector(context);
    }

    public void setShakeListener(ShakeDetector.OnShakeListener onShakeListener){
        shakeDetector.setOnShakeListener(onShakeListener);
        shakeDetector.start();
    }

    @Override
    protected void onDetachedFromWindow() {
        shakeDetector.stop();
        super.onDetachedFromWindow();
    }
}
